#!/bin/bash

fitfile=$1

if [ $# -ne 1  ]
then
	echo "usage: xot.sh a.fit"
	exit 0
fi
Dir_data=`pwd`
Dir_gaia2=~/workspace/gaia_dr2/cached-catalog/gaia_dr2/merge-60cm.csv
FoV=2.0
MAG=19.0

mkdir results

if test -r reduc
then
	rm -rf reduc
fi

Tillname=`echo $Dir_data | tr '/' ' ' | xargs -n 1 | tail -1 | awk '{print($1)}'`
echo $Tillname

if test ! -r results
then
        mkdir results
        cd results
        mkdir $Tillname
        cd $Tillname
        Dir_tillname=`pwd`
        #rm -rf results
else
        cd results
        mkdir $Tillname
        cd $Tillname
         Dir_tillname=`pwd`
fi

cd $Dir_data


dir_getCatalog=$HOME/han/catalogue_v1.2
lowMagTemp=-1.0    #brightest object
largerMagTemp=23.0  #dimest object
dir_usnob10=$HOME/usnob10
RadiusTempArcmin=24.0



   AstroCaliFile=`echo $fitfile | sed 's/\.fit/.new/g'`
    OUTPUT=`echo $fitfile | sed 's/\.fit/.sex/g'`
    OUTPUT_limit=`echo $fitfile | sed 's/\.fit/.sex_limit/g'`
    OUTPUT_limit_new=`echo $fitfile | sed 's/\.fit/.sex_new_limit/g'`
    OTfinalres_limit=`echo $fitfile | sed 's/\.fit/_otfinalres_withlimit.txt/g'`
    prefix=`echo $fitfile | sed 's/\.fit//g'`
    gaialist=`echo $fitfile | sed 's/\.fit/_gaia.txt/g'`
    usnolist=`echo $fitfile | sed 's/\.fit/_usno.txt/g'`
    OUTPUT_new=`echo $fitfile | sed 's/\.fit/.sexnew/g'`
    TempUSNORADEC=`echo $fitfile | sed 's/\.fit/_tempRADEC.txt/g'`
    TempUSNOXY=`echo $fitfile | sed 's/\.fit/_tempXY.txt/g'`
    otxy=`echo $fitfile | sed 's/\.fit/_otxy.txt/g'`
    MonitorFile=`echo $fitfile | sed 's/\.fit/_res.txt/g'`
    matchedfile=`echo $fitfile | sed 's/\.fit/_KnownObjxy.txt/g'`
    compstarsfile=`echo $fitfile | sed 's/\.fit/_compstars.txt/g'`
    OTfile=`echo $fitfile | sed 's/\.fit/_ot.txt/g'`
    checkstarfile=`echo $fitfile | sed 's/\.fit/_checkstarrealxy.txt/g'`
    deltaMagfile=`echo $fitfile | sed 's/\.fit/_deltaMag.txt/g'`
    OTfinalres_withdis=`echo $fitfile | sed 's/\.fit/_otfinalres_withdis.txt/g'`
    OTfinalres=`echo $fitfile | sed 's/\.fit/_otfinalres.txt/g'`
    OTfinalresDiscal=`echo $fitfile | sed 's/\.fit/_otfinalresDisCal.txt/g'`
    OTFieldxyForTvMark=`echo $fitfile | sed 's/\.fit/_otxyfortvmark.txt/g'`
    OTFieldxy=`echo $OTid | awk '{print($1".otxy")}'`
    OTTriggerxy=`echo $OTid | awk '{print($1"_trigger.otxy")}'`
    OTFieldxy_ref=`echo $OTid | awk '{print($1".otxyref")}'`
    OTFieldTemp=`echo $OTid | awk '{print($1".tempcomp")}'`
    OTFieldUSNO=`echo $OTid | awk '{print($1".tempusno")}'`
    OTWCSfit=`echo $OTid | awk '{print($1"_wcs.new.fit")}'`
    RATT=`gethead $fitfile "objctra"`
    DECTT=`gethead $fitfile "objctdec"`
    JD=`gethead $fitfile "jd"`
    deltayear=`echo $JD | awk '{print(($1-2451545.0)/365.25)}'`




xfilterpsf_OT ( )
{
      PSF_Critical_min=3.0
       Dir_now=`pwd`
       cat newOT.txt | awk '{print($1,$2, "  1 a")}' >psf.dat
       cd $HOME/iraf1
       cp -f login.cl.old login.cl
       echo noao >> login.cl
       echo image >> login.cl
       echo digiphot >> login.cl
       echo daophot >>login.cl
       echo "cd $Dir_now" >> login.cl
       echo "daoedit(\"$fitfile\", icommand=\"psf.dat\")"  >> login.cl
       echo logout >> login.cl
       cl < login.cl  >OUTPUT_PSF
       mv OUTPUT_PSF $Dir_now
       cp -f login.cl.old login.cl
       cd $Dir_now
       cat OUTPUT_PSF | grep "ERROR" >errormsg
       if test ! -s errormsg
       then 
           cat OUTPUT_PSF | sed -e '/^$/d' | grep '[1-9]' | grep -v "NOAO" | grep -v "This" | grep -v "line" | grep -v "m" >OUTPUT_PSF1
           paste OUTPUT_PSF1 newOT.txt | awk '{if($5>PSF_Critical_min)print($8,$9,$10,$11,$5)}' PSF_Critical_min=$PSF_Critical_min >temp
           mv temp newOT.txt
       else
           echo "Error in psf checking for OT candidates"
       fi

}

xnomresults ( )
{
	echo "xnomresults"
	dateobs=`gethead $fitfile "date-obs"`
	echo	"#CH dateUtc x y xtemp ytemp ra dec mag magerr fwhm ellipticity stampName probability" >tmp
	cat $OTfile | while read line
	do
		echo $dateobs $line 
	done

}

xPS1cross ( )
{
        echo "xPS1cross"
#to crossmatch with the PS1 catalog 
        wc newOT.txt
        date
        if test -s PS1.txt
        then
                rm -rf PS1.txt
        fi
        echo $RA $DEC
         ~/software/anaconda3/bin/python ~/software/soft60cm/xGetPS1.py $RA $DEC 1800.0  #r=1800.0 arcsec to crossmatch the PS1 catalog and the OT list  
        wait
        if test -s PS1.txt
        then
                cat PS1.txt | grep -v "ra" | tr ',' ' ' | grep -v "nan" | awk '{if($3>0)print($0)}' >tmp
                mv tmp PS1.txt
                sky2xy $fitfile @PS1.txt | grep -v "off" | awk '{print($5,$6)}'>gaia.txt
                xcross30cmOT
                wc newOT.txt
        fi
        date
}



#xlimit.sh $fitfile

LIMITMAG=`gethead $fitfile "LIMITMAG" `
MAG=`echo $LIMITMAG | awk '{print($1+1)}'`


NAXIS1=`gethead $fitfile "NAXiS1"`
NAXIS2=`gethead $fitfile "NAXiS2"`
xcenter=`gethead $fitfile "NAXiS1" | awk '{print($1/2)}'`
ycenter=`gethead $fitfile "NAXiS2" | awk '{print($1/2)}'`

RA=`xy2sky -d $fitfile $xcenter $ycenter | awk '{print($1)}'`
DEC=`xy2sky -d $fitfile $xcenter $ycenter | awk '{print($2)}'`
python ~/software/soft60cm/gwac_search.py ra=$RA dec=$DEC fieldwidth=$FoV  mag=$MAG mergedFileName=merge-60cm.csv
cat $Dir_gaia2 | grep -v "source" |  tr ',' ' ' |  awk '{if($9<limitmag)print($4+($6*deltayear/cos($5*3.1415926/180)/3600/1000),$5+($7*deltayear/3600/1000))}' deltayear=$deltayear limitmag=$MAG >gaia2_source.txt
sky2xy $fitfile @gaia2_source.txt | grep -v "off" | awk '{print($5,$6)}'>gaia.txt

mkdir reduc
cp $fitfile reduc
cd reduc
cp ~/software/soft60cm/* ./
cp ../gaia.txt ./
cp gaia.txt $gaialist

DELTAMAG=`gethead $fitfile "DELTAMAG"`
Detect_sigma=1.5
ejmax=10
sex $fitfile  -c  daofind.sex  -DETECT_THRESH $Detect_sigma -ANALYSIS_THRESH $Detect_sigma -CATALOG_NAME $OUTPUT
cat $OUTPUT | awk '{if($1>ejmax && $2>ejmax && $1<(xccdsize-ejmax) && $2<(yccdsize-ejmax) && $4<0.2  && $7>2)print($1,$2,$3-deltamag,$4,$7)}' deltamag=$DELTAMAG  ejmax=$ejmax xccdsize=$NAXIS1 yccdsize=$NAXIS2 >newobj.txt

xcross30cmOT  #input files are gaia.txt and newobj.txt,   outputfile is newOT.txt

#to crossmatch the usno b1.0
if test -s newOT.txt
then
	cp newOT.txt newobj.txt
	cp $gaialist $Dir_tillname
	#cat newobj.txt
	echo "xGetCatalog"
    	cd $dir_reduction
	echo "~/usnob10/src/usnob1 -R $dir_usnob10 -c $RA $DEC  -r $RadiusTempArcmin -lmr2 0,$MAG -m 2000000 -sr"
    	~/usnob10/src/usnob1 -R $dir_usnob10 -c $RA $DEC  -r $RadiusTempArcmin -lmr2 0,$MAG -m 2000000 -sr >listusnobobj

    	python $dir_usnob10/usnob10_format.py ./ listusnobobj
    	#cat tmp_listusnobobj | awk '{print($1,$2)}' >gaia2_source.txt
	cat tmp_listusnobobj | awk '{print($1+$7*deltayear/cos($2*3.1415926/180)/3600/1000,$2+$8*deltayear/3600/1000,$3,$4,$5,$6)}' deltayear=$deltayear > gaia2_source.txt
    	#output includes ra dec b1 b2 R1 R2 I
    	if test -s gaia2_source.txt
    	then
		mv gaia2_source.txt $Dir_data/reduc
		cd $Dir_data
		cd reduc
        	echo "Geting usno catalog is successful"
		sky2xy $fitfile @gaia2_source.txt | grep -v "off" | awk '{print($5,$6)}'>gaia.txt
		cp gaia.txt $usnolist
		echo "gaia.txt"
		#cat gaia.txt
		echo "================"
	        #mv newOT.txt newobj.txt	
		echo `pwd`
		cat newobj.txt
		xcross30cmOT
    	else
        	echo "Geting catalog failed"
        	echo $Dir_data
        	#exit 0
    	fi
fi


if test -s newOT.txt
then
        cp newOT.txt newobj.txt
        xPS1cross

fi


if test -s newOT.txt
then
	echo "have new OT found in the $fitfile"
	xfilterpsf_OT
	if test -s newOT.txt
	then
		xy2sky $fitfile @newOT.txt >newOT_sky.txt
		paste newOT.txt newOT_sky.txt | column -t >$OTfile
		echo "$OTfile"
#		xnomresults
		mv $OTfile $Dir_tillname
                cp $fitfile $Dir_tillname
		cp $usnolist $Dir_tillname
		#mv $OTfile ../results
	else
		echo "no any new OT found in the $fitfile after the psf filter"
		echo "The limit mag is $LIMITMAG"
	fi
else
	echo "no any new OT found in the $fitfile"
	echo "The limit mag is $LIMITMAG"
fi
cd ../
rm -rf reduc
mv *gladexy $Dir_tillname
#cp *c.fit $Dir_tillname

~/software/soft60cm/xautocopycutimage_2_m93.f  results


